package pl.un4giv3n.mightvsmagic.action;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserType;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia
 * log in user
 */
public class LoginAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;

	/**
	 * username to log in
	 */
	private String username;
	/**
	 * user password
	 */
	private String password;
	/**
	 * logged in user
	 */
	private User user;

	/* (non-Javadoc)
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	@SuppressWarnings("unchecked")
	public String execute() {
		EntityManager entityManager = getEntityManager();
		Query query = entityManager.createNamedQuery("find.user.by.login");
		query.setParameter("login", username);
		List resultList = query.getResultList();
		if (resultList.isEmpty()) {
			addActionError("Użytkownik " + username
					+ " nie istnieje lub nieprawidłowe hasło!");
			entityManager.close();
			return INPUT;
		}
		user = (User)resultList.get(0);
		if(!user.getPassword().equals(UserUtil.encyptPassword(password)) || user.isBlocked()){
			addActionError("Użytkownik " + username
					+ " nie istnieje lub nieprawidłowe hasło!");
			entityManager.close();
			return INPUT;
		}
		if(user.getUserType() == UserType.ADMIN){
			getSession().put(USER_ID, user.getId());
			return ADMIN_PAGE;
		}
		getSession().put(USER_ID, user.getId());
		entityManager.close();
		return SUCCESS;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
